package com.kaipizhe.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;
import java.util.Set;

@Component
public class CustomUrlPatternExtractor implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    private final Map<String, String> packagePrefixMap = Map.of(
            "com.kaipizhe.controller.web", "/web",
            "com.kaipizhe.controller.app", "/app"
    );

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        extractAllUrls();
    }

    public void extractAllUrls() {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo mappingInfo = entry.getKey();
            if (mappingInfo != null) {
                HandlerMethod handlerMethod = entry.getValue();

                String controllerPackage = handlerMethod.getBeanType().getPackage().getName();
                String prefix = getMatchingPrefix(controllerPackage);

                PatternsRequestCondition patternsCondition = mappingInfo.getPatternsCondition();
                if (patternsCondition != null) {
                    Set<String> patterns = patternsCondition.getPatterns();

                    for (String pattern : patterns) {
                        String completeUrl = prefix + pattern;

                        // 检查是否包含路径变量
                        if (pattern.contains("{") && pattern.contains("}")) {
                            System.out.println("Dynamic URL: " + completeUrl);
                            // 这里就能获取到 /web/api/items/type/{id}
                        }
                    }
                }


            }
        }
    }

    private String getMatchingPrefix(String packageName) {
        return packagePrefixMap.entrySet().stream()
                .filter(entry -> packageName.startsWith(entry.getKey()))
                .map(Map.Entry::getValue)
                .findFirst()
                .orElse("");
    }
}
